package com.teamin.service.impl.wx;

import com.alibaba.fastjson.JSONObject;
import com.teamin.security.AESUtils;
import com.teamin.web.Evn;
import com.teamin.web.https.HttpRequest;
import com.teamin.web.https.OkHttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class WXSendMessage  {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    public static final String SEND_MESSAGE_WX_PASSWORD = "fLSF892vpbCi6I163IoRHI5vm2";
    public final static String TEMPLATE_URI = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
    public static ThreadPoolExecutor cachedThreadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(500);
    private static WXSendMessage wm = new WXSendMessage() ;

    private WXSendMessage() {

    }

    public static WXSendMessage getInstance() {
        synchronized (WXSendMessage.class) {
            if(wm == null) {
                wm = new WXSendMessage() ;
            }
        }
        return wm ;
    }

    /**
     * 发送微信消息
     */

    public void postMessage( JSONObject json) {
        cachedThreadPool.execute(new MessageRunnable(json)) ;
    }

    public static class MessageRunnable implements Runnable {

        JSONObject json ;
        public MessageRunnable(JSONObject json ) {
            this.json = json ;
        }

        @Override
        public void run() {
            try {
                if("test".equals(Evn.SERVICE_PROFILS)) {
                    OkHttpRequest.httpsRequest(Evn.SERVICE_URL_MPCARD,"POST",null,AESUtils.encrypt(JSONObject.toJSONString(json),SEND_MESSAGE_WX_PASSWORD)) ;
                }else {
                    JSONObject asscessTokenObject = HttpRequest.request(TEMPLATE_URI + WeChatMPTokenManager.getInstance().getAccessToken(), "POST", JSONObject.toJSONString(json));
                    if (asscessTokenObject.getInteger("errcode") == 40001 || asscessTokenObject.getInteger("errcode") == 42001) { // accessToken
                    }
                    System.out.println(asscessTokenObject.toJSONString());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
